package com.tgb.test;

import java.io.IOException;
import java.util.Arrays;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;


import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.kucun.bean.Users;
import com.times.cache.Cache;
import com.times.constant.Message;
import com.times.exception.BusinessException;
import com.times.exception.NoNecessaryException;
import com.times.exception.SystemException;
import com.times.util.JsonResult;

@Aspect
public class LogAfterAdvice {
	  private final static ObjectMapper jsonMapper = new ObjectMapper();
	  private static final Logger logger = Logger.getLogger(LogAfterAdvice.class.getName());
      @Pointcut("execution(* com.kucun.Dao.*.*(..))") 
	  public void show(){}
      
//      @org.aspectj.lang.annotation.Before("execution(* com.kucun.Dao.*.*(..))")
//      public Object Before(JoinPoint jp) throws Exception{
//		  String date=(new Date()).toLocaleString(); 
//    	  if("login".equals(jp.getSignature().getName())){
//    		  logger.info("执行方法["+jp.getSignature().getName()+"] ["+date+"]用户："+jp.getArgs()[0]+" 登录成功！");         
//    	  }else if("clear".equals(jp.getSignature().getName())){
//    		  logger.info("执行方法["+jp.getSignature().getName()+"] ["+date+"]用户："+jp.getArgs()[0]+" 下线！");         
//    	  }
//		  
//    	   return null;  
//      }
      
      
	  @After(value="show()")
	  public Object after(JoinPoint jp) throws Exception{	
		  Object o = null;
		  HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); 
		/* JsonResult result=new JsonResult();
		 if(jp instanceof JsonResult){
			 return jsonMapper.writeValueAsString(jp);
		 }
		 Object[] obj=jp.getArgs();
		 System.out.println("拦截器中获取的参数===");
		  log.info(UsersController.userna+"调用了"+jp.getTarget()+"的"+jp.getSignature().getName() +"方法：方法入参"+Arrays.toString(jp.getArgs()));
		  return o;*/
		  Users user=(Users)request.getSession().getAttribute("user");
		  
		  //logger.info(user.getUsername()+"调用了"+jp.getTarget()+"的"+jp.getSignature().getName() +"方法：方法入参"+Arrays.toString(jp.getArgs()));
		  JsonResult result = new JsonResult(); 
	        try { 
	            Object obj = jp.getArgs();
	            if(obj instanceof JsonResult){
	                return jsonMapper.writeValueAsString(obj);
	            }
	            result.setSuccess(true);
	            result.setCode(Message.SUCCESS);
	            result.setMsg(Cache.getProperty(Message.SUCCESS));
	            result.setData(obj);
	        } catch (NoNecessaryException e) {// 不需要的操作，不需要设置code
	            logger.debug(String.format("occur no necessary error：%s", e.getMessage()));
	            result.setMsg(e.getMessage());
	        } catch (BusinessException e) {
	            logger.debug(String.format("occur business error：%s", e.getMessage()));
	            result.setCode(e.getCode());
	            result.setMsg("业务异常："+e.getMessage());
	        } catch (SystemException e) {
	            logger.error(String.format("occur system error：%s", e));
	            result.setCode(e.getCode());
	            result.setMsg("系统异常："+e.getMessage() + "，请联系系统管理员");
	        } catch (Exception e) {
	            logger.error(String.format("occur inner server error：%s", e));
	            result.setCode(Message.INNER_SERVER_ERROR);
	            result.setMsg(Cache.getProperty(Message.INNER_SERVER_ERROR) + "，请联系系统管理员");
	        }
	        try {
	            //mapper.writerWithDefaultPrettyPrinter().writeValueAsString(bean); //将字符串美化成多行
	        	if(user!=null){
	        		logger.info(user.getUsername()+"调用方法["+ jp.getSignature().getName()+"] 相关数据："+ jsonMapper.writeValueAsString(result));
	  		  }
	        	return jsonMapper.writeValueAsString(result);
	        } catch (IOException e) {
	            logger.error(e.getMessage());
	        } finally {
	            result = null;
	        }
	        return null;
		  
	  }
	  
}

